import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';

import 'logic.dart';
import 'state.dart';

class LocalLifePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LocalLifePageState();
  }
}

class _LocalLifePageState extends State<LocalLifePage> {
  final LocalLifeLogic logic = Get.put(LocalLifeLogic());
  final LocalLifeState state = Get.find<LocalLifeLogic>().state;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LocalLifeLogic>(
      builder: (logic) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Color.fromRGBO(254, 88, 2, 1),
            title: Text(
              '本地生活',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
            elevation: 0,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.white,
              ),
              onPressed: () {
                // Get.offAllNamed(RouteConfig.mainApp);
                Get.back();
              },
            ),
          ),
          body: Container(
            color: Colors.white,
            child: Column(
              children: [
                if(state.tips!='') SizedBox(width:100,height:100),
                  if(state.tips!='') Align( alignment: Alignment.center , child:Text(state.tips)),
                _bannerWidget(),
                Expanded(
                  child: ListView.builder(
                    padding: EdgeInsets.zero,
                    shrinkWrap: true,
                    itemCount: state.shopInfosList.length,
                    itemBuilder: (context, index) {
                      // if (index == 0) {
                      //   return _bannerWidget();
                      // }
                      return _storeInformation(index: index);
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 轮播图
  Widget _bannerWidget({
    Map<String, dynamic> dataMap,
  }) {
    // // var bannerMap = convert.jsonDecode(dataMap['widgets_data_params']);
    // // double ratio, height;
    // // if (bannerMap['ratio'] == null || bannerMap['ratio'] == '') {
    // //   if (bannerMap['height'] == null || bannerMap['height'] == '') {
    // //     height = 220;
    // //   } else {
    // //     height = double.parse(bannerMap['height'].toString());
    // //   }
    // // } else {
    // //   ratio = double.parse(bannerMap['ratio'].toString());
    // //   height = (MediaQuery.of(context).size.width - 20) / ratio;
    // // }
    // // height = height + 20;
    // // List bannerList = bannerMap['pictures'];
    // //
    // // DateTime currentTime = DateTime.now();
    // // DateTime beginTime;
    // // DateTime endTime;
    // // List listBannerMap = [];
    // // for (int i = 0; i < bannerList.length; i ++) {
    // //   var map = bannerList[i];
    // //   String begin_time = map['begin_time'] ?? '';
    // //   String end_time = map['end_time'] ?? '';
    // //   if (begin_time != '' && end_time != '') {
    // //     beginTime = DateTime.parse('${map['begin_time']}');
    // //     endTime = DateTime.parse('${map['end_time']}');
    // //     if (currentTime.isAfter(beginTime) && currentTime.isBefore(endTime)) {
    // //       listBannerMap.add(map);
    // //     }
    // //   } else if (begin_time != '' && end_time == '') {
    // //     beginTime = DateTime.parse('${map['begin_time']}');
    // //     if (currentTime.isAfter(beginTime)) {
    // //       listBannerMap.add(map);
    // //     }
    // //   } else if (begin_time == '' && end_time != '') {
    // //     endTime = DateTime.parse('${map['end_time']}');
    // //     if (currentTime.isBefore(endTime)) {
    // //       listBannerMap.add(map);
    // //     }
    // //   } else {
    // //     listBannerMap.add(map);
    // //   }
    // // }
    //
    // Map<String, dynamic> bannerMap;
    // for (int i = 0; i < state.templateList.length; i++) {
    //   var dataMap = state.templateList[i];
    //   if (dataMap['widgets_sign'] == 1) {
    //     bannerMap = dataMap;
    //     break;
    //   }
    // }
    // if (bannerMap == null) {
    //   return Container();
    // }
    //
    // var bannerDataMap = convert.jsonDecode(bannerMap['widgets_data_params']);
    // double height;
    // if (bannerDataMap['height'] == null || bannerDataMap['height'] == '') {
    //   height = 220.0 * 2.0 + 40.0;
    // } else {
    //   height = double.parse(bannerDataMap['height'].toString()) * 2.0 + 40.0;
    // }
    // List bannerList = bannerDataMap['pictures'];

    print("state.templateList");
    return Container(
      padding: EdgeInsets.symmetric(horizontal: setWidth(20)),
      child: Container(
        height: setWidth(390),
        padding: EdgeInsets.only(
          top: setWidth(20),
          bottom: setWidth(20),
        ),
        child: state.templateList.length == 0
            ? SizedBox()
            : Swiper(
                // key: ValueKey('${bannerList.length.toString()}'),
                // key: ValueKey('localLifeBanner'),
                autoplay: false,
                onTap: (int index) {
                  // Map map = bannerList[index];
                  // print('++++ onTap ++++ 点击事件！！！ map = $map');
                  // // jump(
                  // //   url: map['linktype'].toString(),
                  // //   model: map,
                  // // );
                },
                itemCount: state.templateList.length, //bannerList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(setWidth(10)),
                      child: CachedNetworkImage(
                        imageUrl: state.templateList[index]
                            ['pic_url'], //bannerList[index]['pic_url'],
                        width: MediaQuery.of(context).size.width - 20,
                        height: setWidth(350), //setWidth((height - 40.0) / 2),
                        fit: BoxFit.fill,
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            'assets/images/localLifeBanner.png',
                            width: MediaQuery.of(context).size.width - 20,
                            height: setWidth(350),
                            fit: BoxFit.fill,
                          );
                        },
                      ),
                    ),
                  );
                },
                // pagination: SwiperPagination(),
              ),
      ),
    );
  }

  // 店铺信息
  Widget _storeInformation({int index}) {
    Map<String, dynamic> map = state.shopInfosList[index];

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            color: Color(0xffe0e0e0),
            width: setWidth(1),
          ),
        ),
      ),
      height: setWidth(170),
      padding: EdgeInsets.symmetric(
          horizontal: setWidth(20), vertical: setWidth(20)),
      child: InkWell(
        onTap: () {
          print('=======------------=============  map = $map');
          logic.getAndGoThirdShop(map['ec_shop_num_id']);
        },
        child: Row(
          children: [
            (map['ec_shop_logo'] == null || map['ec_shop_logo'] == '')
                ? Container(
                    width: setWidth(130),
                    height: setWidth(130),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(setWidth(10)),
                      border: Border.all(
                        width: setWidth(1),
                        color: Color(0xffdddddd),
                      ),
                    ),
                    child: Image.network(Config.orderEmpty)
                    // child: Text(
                    //   '暂无\n图片',
                    //   style: TextStyle(
                    //     color: Color(0xffdddddd),
                    //     fontSize: 15,
                    //   ),
                    // ),
                    )
                : ClipRRect(
                    borderRadius: BorderRadius.circular(setWidth(10)),
                    child: cacheImage(
                        imageUrl: map['ec_shop_logo'],
                        width: setWidth(130),
                        height: setWidth(130),
                        fit: BoxFit.cover),
                  ),
            SizedBox(width: setWidth(10)),
            Expanded(
              child: Container(
                height: setWidth(130),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            map['sub_unit_name'] ?? '', // '慧生活总店测试',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              color: Color(0xff222222),
                              fontSize: 15,
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            print('打电话 点击事件！！！ ${map['telphone']}');
                            launch("tel://${map['telphone']}");
                          },
                          child: Container(
                            width: setWidth(45),
                            height: setWidth(33),
                            child: Icon(
                              Icons.phone,
                              size: setWidth(25),
                              color: Color(0xffeeeeee),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.red.withOpacity(0.8),
                          width: setWidth(1),
                        ),
                        borderRadius: BorderRadius.circular(setWidth(4)),
                      ),
                      child: Text(
                        '营业时间：\n${DateFormat("HH:mm").format(DateTime.parse(map['free_start_time']))}'
                        '- ${DateFormat("HH:mm").format(DateTime.parse(map['free_end_time']))}',
                        textAlign: TextAlign.left,
                        style: TextStyle(
                          color: Colors.red.withOpacity(0.8),
                          fontSize: 10,
                          height: 1.3,
                        ),
                      ),
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            map['sub_unit_adr'] ?? '', // '大运软件小镇',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              color: Color(0xffaaaaaa),
                              fontSize: 12,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: setWidth(10),
                        ),
                        Text(
                          '${map['distance'] ?? '0'}${map['unit']}',
                          style: TextStyle(
                            color: Color(0xff444444),
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
